//go:build !windows
// +build !windows

package signal

import (
	"go.uber.org/zap"
	"gobase/logger"
	"os"
	"os/signal"
	"syscall"
)

var signalFuncList []func()

func init() {
	signalFuncList = make([]func(), 0, 10)
}

// AddSignalFunc 添加信号处理函数,用于主进程退出时调用
func AddSignalFunc(signalFunc func()) {
	signalFuncList = append(signalFuncList, signalFunc)
}

// WaitSignal 等待信号,一般用于主进程阻塞等待退出信号
func WaitSignal() {
	logger.Debug("wait signal")
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP, syscall.SIGKILL)
	for {
		select {
		case a := <-c:
			logger.Debug("receive exit signal", zap.String("signal", a.String()))
			for _, s := range signalFuncList {
				s()
			}
			os.Exit(1)
			return
		}
	}
}
